<?php
/**
 * Created by PhpStorm.
 * User: Aaron
 * Date: 2019/5/20
 * Time: 11:54
 */
namespace Inter\Controller;

use Think\Controller;

class BaseController extends Controller
{
    public function __construct()
    {
        // 跨域请求
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        header('Content-type:application/json');
        parent::__construct();
    }

    /**
     * 数据返回
     *
     * @param $data
     * @param int $code
     * @param string $message
     * @return false|string
     */
    protected function _returnJson($data, $code = 200, $message = '成功')
    {
        if (empty($data)) {
            $data = array();
        }

        $data = array(
            'code'    => $code,
            'message' => $message,
            'data'    => $data
        );
        return json_encode($data);
    }


    /**
     * 创建token
     */
    protected function create_token($id) {
        $rand = md5(rand(1000, 99999).$id);
        S($rand, $id, C('EXPIRE'));
        return $rand;
    }

    /**
     *  读取token
     */
    protected function read_token($token) {
        return S($token);
    }

    /**
     *  删除token
     */
    protected function delete_token($token) {
        S($token, null);
    }


    /**
     * 鉴权
     */
    protected function requestAuth()
    {
        $get_token = I('get.token');
        $post_token = I('post.token');
        $token = empty($get_token) ? $post_token : $get_token;
        if (empty($token)){
            return false;
        }
        return $this->read_token($token);
    }

}